package org.example.servlet;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.entity.Employee;
import org.example.service.EmployeeService;
import org.example.service.HrService;
import org.example.utils.ResultTools;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;


@WebServlet(urlPatterns = {"/login", "/addEmployee", "/updateEmployee", "/deleteEmployee", "/employeeList", "/queryEmployee"})
public class MyHttpServlet extends HttpServlet {
    private final static String REMEMBER_PASSWORD = "isLogin";
    private final static String LOGIN_SUCCESS = "登录成功";
    private final static String LOGIN = "/login";
    private final static String ADD = "/addEmployee";
    private final static String UPDATE = "/updateEmployee";
    private final static String DELETE = "/deleteEmployee";
    private final static String QUERY_ALL = "/employeeList";
    private final static String QUERY_EMPLOYEE = "/queryEmployee";
    private final static String URL = "<a href='http://localhost:8080/springMybatis/welcome.jsp'>返回欢迎页面</a><br/>";
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");

    HrService hrService = context.getBean(HrService.class);
    EmployeeService employeeService = context.getBean(EmployeeService.class);


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getServletPath();
        switch (action) {
            case LOGIN:
                login(request, response);
                break;
            case ADD:
                add(request, response);
                break;
            case UPDATE:
                update(request, response);
                break;
            case DELETE:
                delete(request, response);
                break;
            case QUERY_ALL:
                queryAll(request, response);
                break;
            case QUERY_EMPLOYEE:
                queryEmployee(request, response);
                break;
            default:
                break;
        }

    }


    public void queryAll(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {


        String pageNumStr = request.getParameter("pageNum");
        String pageSizeStr = request.getParameter("pageSize");
        int pageNum = 1;
        int pageSize = 10;
        if (pageSizeStr != "" || null != pageSizeStr) {
            pageSize = Integer.valueOf(pageSizeStr);
        }
        if (pageNumStr != "" || null != pageNumStr) {
            pageNum = Integer.valueOf(pageNumStr);
        }


        PageHelper.startPage(pageNum, pageSize);
        List<Employee> employees = employeeService.queryAll();
        PageInfo pageInfo = new PageInfo(employees, 10);
        request.setAttribute("pageInfo", pageInfo);
        Cookie cookie = new Cookie("pageNum", String.valueOf(pageNum));
        response.addCookie(cookie);
        request.getRequestDispatcher("employeeList.jsp").forward(request, response);
    }


    public void queryEmployee(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("id");
        ResultTools resultTools = new ResultTools();
        if (idStr != "") {
            int id = Integer.valueOf(idStr);
            Employee employee = employeeService.queryEmployee(id);
            resultTools.setData(employee);
        } else {
            resultTools.setMsg("查无此人");
        }
        request.setAttribute("result", resultTools);
        request.getRequestDispatcher("updateEmployee.jsp").forward(request, response);
    }


    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String msg = hrService.login(username, password);
        if (LOGIN_SUCCESS.equals(msg)) {
            if (null != request.getParameter(REMEMBER_PASSWORD)) {
                Cookie username1 = new Cookie("username", username);
                response.addCookie(username1);
            }
            HttpSession session = request.getSession();
            session.setAttribute("username", username);
            request.getRequestDispatcher("welcome.jsp").forward(request, response);
        } else {
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }
    }


    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Integer id = Integer.valueOf(request.getParameter("id"));
        if (employeeService.deleteEmployee(id)) {
            request.getRequestDispatcher("welcome.jsp").forward(request, response);
        }
    }


    private void update(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Integer id = Integer.valueOf(request.getParameter("id"));
        PrintWriter out = response.getWriter();
        if (null != employeeService.queryEmployee(id)) {
            Employee employee = addAndUpdate(request);
            employee.setId(id);
            if (employeeService.updateEmployee(employee)) {
                out.print(URL + "<p>修改成功</p>");
                request.getRequestDispatcher("welcome.jsp").forward(request, response);
            } else {
                out.print(URL + "<p>修改失败</p>");
            }
        } else {
            out.print(URL + "<p>未查到该用户</p>");
        }

    }


    private void add(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Employee employee = addAndUpdate(request);
        PrintWriter out = response.getWriter();
        if (employeeService.addEmployee(employee)) {
            out.print(URL + "<p>添加成功</p>");
            request.getRequestDispatcher("welcome.jsp").forward(request, response);
        } else {
            out.print(URL + "<p>添加失败</p>");
        }
    }


    public Employee addAndUpdate(HttpServletRequest request) {
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        String wedlock = request.getParameter("wedlock");

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDateTime format = LocalDate.parse(birthday, dateTimeFormatter).atStartOfDay();
        Date date = Date.from(format.atZone(ZoneId.systemDefault()).toInstant());
        Employee employee = new Employee(name, gender, date, wedlock);
        return employee;
    }

}
